package com.xuetang.service.impl;

import com.xuetang.entity.*;
import com.xuetang.mapper.*;
import com.xuetang.service.DietService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 饮食管理服务实现类
 */
@Service
public class DietServiceImpl implements DietService {

    @Autowired
    private DietFoodCategoryMapper categoryMapper;

    @Autowired
    private DietFoodMapper foodMapper;

    @Autowired
    private DietRecordMapper recordMapper;

    @Autowired
    private DietRecordDetailMapper recordDetailMapper;

    @Autowired
    private DietRecipeMapper recipeMapper;

    @Autowired
    private DietRecipeDetailMapper recipeDetailMapper;

    @Autowired
    private DietRecipeStepMapper recipeStepMapper;

    @Override
    public List<DietFoodCategory> getFoodCategories() {
        return categoryMapper.listAll();
    }

    @Override
    public Map<String, Object> getFoodsByCategory(Integer categoryId, Integer page, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();

        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        int offset = (page - 1) * pageSize;

        List<DietFood> list = foodMapper.listByCategoryId(categoryId, offset, pageSize);
        int total = foodMapper.countByCategoryId(categoryId);

        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    public Map<String, Object> searchFoods(String keyword, Integer page, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();

        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        int offset = (page - 1) * pageSize;

        List<DietFood> list = foodMapper.search(keyword, offset, pageSize);
        int total = foodMapper.countByKeyword(keyword);

        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    public DietFood getFoodDetail(Integer id) {
        return foodMapper.getById(id);
    }

    @Override
    public boolean addFood(DietFood food) {
        if (food == null) {
            return false;
        }

        food.setCreateTime(new Date());
        food.setUpdateTime(new Date());
        food.setStatus(1);

        return foodMapper.insert(food) > 0;
    }

    @Override
    public boolean updateFood(DietFood food) {
        if (food == null || food.getId() == null) {
            return false;
        }

        food.setUpdateTime(new Date());

        return foodMapper.update(food) > 0;
    }

    @Override
    public boolean deleteFood(Integer id) {
        if (id == null) {
            return false;
        }

        return foodMapper.delete(id) > 0;
    }

    @Override
    public DietRecord getDietRecord(Long userId, Date date) {
        DietRecord record = recordMapper.getByUserIdAndDate(userId, date);

        if (record != null) {
            List<DietRecordDetail> details = recordDetailMapper.listByRecordId(record.getId().intValue());
            record.setMeals(details);
        }

        return record;
    }

    @Override
    public Map<String, Object> getDietRecords(Long userId, Date startDate, Date endDate, Integer page,
            Integer pageSize) {
        Map<String, Object> result = new HashMap<>();

        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        int offset = (page - 1) * pageSize;

        List<DietRecord> list = recordMapper.listByDateRange(userId, startDate, endDate, offset, pageSize);
        int total = recordMapper.countByDateRange(userId, startDate, endDate);

        // 获取每个记录的明细
        for (DietRecord record : list) {
            List<DietRecordDetail> details = recordDetailMapper.listByRecordId(record.getId().intValue());
            record.setMeals(details);
        }

        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    @Transactional
    public boolean addDietRecord(DietRecord record, List<DietRecordDetail> details) {
        if (record == null) {
            return false;
        }

        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());

        // 插入记录
        if (recordMapper.insert(record) <= 0) {
            return false;
        }

        // 插入明细
        if (details != null && !details.isEmpty()) {
            for (DietRecordDetail detail : details) {
                detail.setRecordId(record.getId().intValue());
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
            }

            recordDetailMapper.batchInsert(details);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean updateDietRecord(DietRecord record, List<DietRecordDetail> details) {
        if (record == null || record.getId() == null) {
            return false;
        }

        record.setUpdateTime(new Date());

        // 更新记录
        if (recordMapper.update(record) <= 0) {
            return false;
        }

        // 删除旧明细 - 将Long类型转换为Integer
        recordDetailMapper.deleteByRecordId(record.getId().intValue());

        // 插入新明细
        if (details != null && !details.isEmpty()) {
            for (DietRecordDetail detail : details) {
                detail.setRecordId(record.getId().intValue());
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
            }

            recordDetailMapper.batchInsert(details);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean deleteDietRecord(Long id) {
        if (id == null) {
            return false;
        }

        // 删除明细 - 将Long类型转换为Integer
        recordDetailMapper.deleteByRecordId(id.intValue());

        // 删除记录
        return recordMapper.delete(id) > 0;
    }

    @Override
    public Map<String, Object> getRecommendRecipes(Integer page, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();

        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        int offset = (page - 1) * pageSize;

        List<DietRecipe> list = recipeMapper.listByPage(offset, pageSize);
        int total = recipeMapper.count();

        // 获取每个食谱的明细和步骤
        for (DietRecipe recipe : list) {
            // 获取食材明细
            List<DietRecipeDetail> details = recipeDetailMapper.listByRecipeId(recipe.getId());
            recipe.setMeals(details);

            // 获取烹饪步骤
            List<DietRecipeStep> steps = recipeStepMapper.listByRecipeId(recipe.getId());
            recipe.setSteps(steps);
        }

        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    public Map<String, Object> getRecipesByMealType(String mealType, Integer page, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();

        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        int offset = (page - 1) * pageSize;

        List<DietRecipe> list = recipeMapper.listByMealType(mealType, offset, pageSize);
        int total = recipeMapper.countByMealType(mealType);

        // 获取每个食谱的明细和步骤
        for (DietRecipe recipe : list) {
            // 获取食材明细
            List<DietRecipeDetail> details = recipeDetailMapper.listByRecipeId(recipe.getId());
            recipe.setMeals(details);

            // 获取烹饪步骤
            List<DietRecipeStep> steps = recipeStepMapper.listByRecipeId(recipe.getId());
            recipe.setSteps(steps);
        }

        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    public DietRecipe getRecipeDetail(Integer id) {
        DietRecipe recipe = recipeMapper.getById(id);

        if (recipe != null) {
            // 获取食谱明细（食材）
            List<DietRecipeDetail> details = recipeDetailMapper.listByRecipeId(recipe.getId());
            recipe.setMeals(details);

            // 获取食谱步骤
            List<DietRecipeStep> steps = recipeStepMapper.listByRecipeId(recipe.getId());
            recipe.setSteps(steps);
        }

        return recipe;
    }

    @Override
    @Transactional
    public boolean addRecipe(DietRecipe recipe, List<DietRecipeDetail> details) {
        if (recipe == null) {
            return false;
        }

        recipe.setCreateTime(new Date());
        recipe.setUpdateTime(new Date());
        recipe.setStatus(1);

        // 插入食谱
        if (recipeMapper.insert(recipe) <= 0) {
            return false;
        }

        // 插入明细
        if (details != null && !details.isEmpty()) {
            for (DietRecipeDetail detail : details) {
                detail.setRecipeId(recipe.getId());
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
            }

            recipeDetailMapper.batchInsert(details);
        }

        // 插入步骤
        List<DietRecipeStep> steps = recipe.getSteps();
        if (steps != null && !steps.isEmpty()) {
            for (DietRecipeStep step : steps) {
                step.setRecipeId(recipe.getId());
                step.setCreateTime(new Date());
                step.setUpdateTime(new Date());
            }

            recipeStepMapper.batchInsert(steps);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean updateRecipe(DietRecipe recipe, List<DietRecipeDetail> details) {
        if (recipe == null || recipe.getId() == null) {
            return false;
        }

        recipe.setUpdateTime(new Date());

        // 更新食谱
        if (recipeMapper.update(recipe) <= 0) {
            return false;
        }

        // 删除旧明细
        recipeDetailMapper.deleteByRecipeId(recipe.getId());

        // 删除旧步骤
        recipeStepMapper.deleteByRecipeId(recipe.getId());

        // 插入新明细
        if (details != null && !details.isEmpty()) {
            for (DietRecipeDetail detail : details) {
                detail.setRecipeId(recipe.getId());
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
            }

            recipeDetailMapper.batchInsert(details);
        }

        // 插入新步骤
        List<DietRecipeStep> steps = recipe.getSteps();
        if (steps != null && !steps.isEmpty()) {
            for (DietRecipeStep step : steps) {
                step.setRecipeId(recipe.getId());
                step.setCreateTime(new Date());
                step.setUpdateTime(new Date());
            }

            recipeStepMapper.batchInsert(steps);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean deleteRecipe(Integer id) {
        if (id == null) {
            return false;
        }

        // 删除明细
        recipeDetailMapper.deleteByRecipeId(id);

        // 删除步骤
        recipeStepMapper.deleteByRecipeId(id);

        // 删除食谱
        return recipeMapper.delete(id) > 0;
    }

    @Override
    public Map<String, Object> getDietStats(Long userId, Date startDate, Date endDate) {
        // 实现饮食统计数据的获取
        // 此处为示例代码，需要根据实际业务逻辑完善
        Map<String, Object> result = new HashMap<>();

        // 可以根据需求添加其他统计数据
        result.put("stats", "统计数据示例");

        return result;
    }

    @Override
    public int countFoods() {
        return foodMapper.count();
    }

    @Override
    public int countRecipes() {
        return recipeMapper.count();
    }

    @Override
    public int countDietRecords(Date startDate, Date endDate) {
        return recordMapper.countByDateRange(null, startDate, endDate);
    }

    @Override
    public List<DietFood> getRecentFoods(int limit) {
        return foodMapper.listRecent(limit);
    }

    @Override
    public DietRecord getDietRecordById(Long id) {
        if (id == null) {
            return null;
        }
        return recordMapper.getById(id);
    }

    @Override
    public List<DietRecordDetail> getDietRecordDetails(Long recordId) {
        if (recordId == null) {
            return new ArrayList<>();
        }
        return recordDetailMapper.listByRecordId(recordId.intValue());
    }
}